package 算法.leetcode.labuladong.数组和链表;

/**
 * @author lchenglong
 * @date 2022/6/15
 */
public class Difference {
    //差分数组
    private int[] diff ;

    // 构造一个差分数组,区间操作将在这个数组操作
    public Difference(int[] nums){
        assert nums.length>0;
        diff = new int[nums.length];
        diff[0] = 0;
        for (int i=1;i<nums.length;i++) {
            diff[i] = nums[i] - nums[i-1];
        }
    }
    // 给闭区间[i,j]增加val
    public void increment(int i,int j,int val) {
        // 1. 对i...nums.length+val
        diff[i] += val;
        // 2. 对j...nums.length-val
        if (j +1 < diff.length){
            diff[j+1] -= val;
        }
        // 1. 2. 等价于 对 i...j + val
    }

    public int[] result() {
        int[] ans = new int[diff.length];
        ans[0] = diff[0];
        // 根据差分数组构造结果数组
        for (int i=1;i<ans.length;i++) {
            ans[i] = ans[i-1] +diff[i];
        }
        return ans;
    }

}
